<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\bill;

use app\helper\Time;
use think\facade\Db;
use think\exception\ValidateException;
use app\common\dao\bill\BillCatalogDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\energy\EnergyMeterRepository;
use app\common\repositories\energy\EnergyPlanRepository;
use app\common\repositories\energy\EnergyBillRepository;
use app\common\repositories\contract\ContractBillRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;

/**
 * Class BillCatalogRepository
 *
 * @mixin BillCatalogDao
 */
class BillCatalogRepository extends BaseRepository
{

    public function __construct(BillCatalogDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'cateInfo' => function ($query) {
                    $query->bind(['cate_name']);
                },
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
                'billBasicInfo' => function ($query) {
                    $query->field('id,number');
                    $query->bind(['number' => 'number']);
                },
            ])
            ->append(['use_num_z', 'stay_pay_amount', 'check_pay_amount'])
            ->order('id', 'desc')
            ->select();
        foreach ($list as $k => &$v) {
            if ($v['overdue_fine'] <= 0) {
                $v['overdue_fine'] = '--';
            }
            if ($v['use_num_z'] <= 0) {
                $v['use_num_z'] = '--';
            }
            if ($v['minus_amount'] <= 0) {
                $v['minus_amount'] = '--';
            }
        }
        return compact('count', 'list');
    }

    public function addInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $data['total_amount'] = $data['amount'];
            $info = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'BILL.CATALOG.OTHER.ADD', $data);
            return $info;
        });
    }


    public function addBasicInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $data['total_amount'] = $data['amount'];
            $info = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'BILL.CATALOG.BASIC.ADD', $data);
            return $info;
        });
    }

    public function addEnengyInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            /** @var EnergyPlanRepository $energyPlanRepository */
            $energyPlanRepository = app()->make(EnergyPlanRepository::class);
            $planInfo = $energyPlanRepository->get($data['plan_id'])->toArray();

            /** @var EnergyBillRepository $energyBillRepository */
            $energyBillRepository = app()->make(EnergyBillRepository::class);
            $energyBillData = $data['energyBill'];
            unset($data['energyBill']);
            $energyBillData = $energyBillRepository->summaryBillSettlement($energyBillData, $planInfo);
            $energyBillData['property_id'] = $propertyId;
            $energyBillData['room_id'] = $data['room_id'];
            if (isset($planInfo) && is_array($planInfo)) {
                $energyBillData['plan_record'] = json_encode($planInfo, JSON_UNESCAPED_UNICODE);
            }
            $energyBillInfo = $energyBillRepository->create($energyBillData);

            $data['property_id'] = $propertyId;
            $data['energy_bill_id'] = $energyBillInfo['id'];
            $data['amount'] = $energyBillInfo['total_amount'];
            $data['total_amount'] = $energyBillInfo['total_amount'];
            $info = $this->dao->create($data);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'BILL.CATALOG.ENERGY.ADD', $data);
            return $info;
        });

    }

    public function addOtherInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $data['total_amount'] = $data['amount'];
            $info = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'BILL.CATALOG.OTHER.ADD', $data);
            return $info;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            if ($info['energy_bill_id'] > 0) {
                /** @var EnergyPlanRepository $energyPlanRepository */
                $energyPlanRepository = app()->make(EnergyPlanRepository::class);
                $planInfo = $energyPlanRepository->get($data['plan_id'])->toArray();
                /** @var EnergyBillRepository $energyBillRepository */
                $energyBillRepository = app()->make(EnergyBillRepository::class);
                $energyBillData = $data['energyBill'];
                $isSettle = $data['is_settle'] ?? 0;
                unset($data['is_settle']);
                $energyBillData = $energyBillRepository->summaryBillSettlement($energyBillData, $planInfo);
                $totalAmount = $energyBillData['total_amount'];
                unset($energyBillData['total_amount']);
                if (isset($planInfo) && is_array($planInfo)) {
                    $energyBillData['plan_record'] = json_encode($planInfo, JSON_UNESCAPED_UNICODE);
                }
                $energyBillRepository->energyBillUpdate($info['energy_bill_id'], $energyBillData);
                $data['amount'] = $totalAmount;

                if ($isSettle == 1 && $info['energy_id'] > 0) {
                    /** @var EnergyMeterRepository $energyMeterRepository */
                    $energyMeterRepository = app()->make(EnergyMeterRepository::class);
                    $updateData = [
                        'base_z' => $data['end_num_z'],
                        'base_j' => $data['end_num_j'],
                        'base_f' => $data['end_num_f'],
                        'base_p' => $data['end_num_p'],
                        'base_g' => $data['end_num_g'],
                    ];
                    $energyMeterRepository->energyMeterUpdate($info['energy_id'], $updateData);
                }
            }

            $data['total_amount'] = $data['amount'];
            if (isset($info['overdue_fine']) && $info['overdue_fine'] > 0) {
                $data['total_amount'] = bcadd($info['overdue_fine'], $data['amount'], 2);
            }
            if (isset($data['minus_amount']) && $data['minus_amount'] > 0) {
                $data['total_amount'] = bcsub($data['total_amount'], $data['minus_amount'], 2);
            }

            unset($data['plan_id']);
            unset($data['energyBill']);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'BILL.CATALOG.EDIT', $data);
            return $this->update($info['id'], $data);
        });
    }


    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->with([
                'cateInfo' => function ($query) {
                    $query->bind(['full_cate_name']);
                },
                'roomInfo' => function ($query) {
                    $query->bind(['full_room_name']);
                },
                'billBasicInfo' => function ($query) {
                    $query->bind(['overdue_day' => 'overdue_day', 'cutoff_date' => 'cutoff_date']);
                }
            ])
            ->append(['energy_bill_info'])
            ->where('id', $id)
            ->find();
        if ($data['overdue_fine'] <= 0) {
            $data['overdue_fine'] = '--';
        }
        if ($data['overdue_day'] <= 0) {
            $data['overdue_day'] = '--';
        }
        if ($data['minus_amount'] <= 0) {
            $data['minus_amount'] = '--';
        }
        return $data;
    }

    public function getApiBillIdDetail(int $billId)
    {
        $data = $this->dao->getSearch([])
            ->where('bill_id', $billId)
            ->with([
                'cateInfo' => function ($query) {
                    $query->bind(['cate_name']);
                }
            ])
            ->field('id,bill_id,cate_id,is_shared,energy_bill_id,overdue_fine,amount,minus_amount,total_amount,start_date,end_date,remark,status,refund_type,refund_amount,refund_date')
            ->append(['use_num_z', 'stay_pay_amount', 'check_pay_amount'])
            ->select();
        return $data;
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ], 'id,property_id,bill_id,cate_id,total_amount');
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        event('bill.catalog.delete', [
            'billCatalogInfo' => $info,
            'userId' => $userId
        ]);
        $this->dao->delete($info['id']);
    }

    public function addAll($billInfo, array $data, int $remark = null)
    {
        /** @var EnergyBillRepository $energyBillRepository */
        $energyBillRepository = app()->make(EnergyBillRepository::class);

        /** @var BillCateRepository $cateRepository */
        $cateRepository = app()->make(BillCateRepository::class);
        $insertData = [];
        foreach ($data as $k => $v) {
            if ($v) {
                $cateInfo = $cateRepository->get($v['cate_id']);
                $energyBillId = 0;
                $energyBillInfo = [];
                if ($cateInfo['is_class'] == 2 && $cateInfo['set_finance'] == 11) {
                    $energyBillData['energy_type'] = 11;
                    $energyBillInfo = $energyBillRepository->create($energyBillData);
                } elseif ($cateInfo['is_class'] == 2 && $cateInfo['set_finance'] == 12) {
                    $energyBillData['energy_type'] = 12;
                    $energyBillInfo = $energyBillRepository->create($energyBillData);
                } elseif ($cateInfo['is_class'] == 2 && $cateInfo['set_finance'] == 13) {
                    $energyBillData['energy_type'] = 13;
                    $energyBillInfo = $energyBillRepository->create($energyBillData);
                } elseif ($cateInfo['is_class'] == 2 && $cateInfo['set_finance'] == 14) {
                    $energyBillData['energy_type'] = 14;
                    $energyBillInfo = $energyBillRepository->create($energyBillData);
                }
                if ($energyBillInfo) {
                    $energyBillId = $energyBillInfo['id'];
                }
                $insertData[] = [
                    'status' => 1,
                    'remark' => $remark,
                    'amount' => $v['amount'],
                    'total_amount' => $v['amount'],
                    'cate_id' => $v['cate_id'],
                    'energy_bill_id' => $energyBillId,
                    'bill_id' => $billInfo['id'],
                    'start_date' => $v['start_date'],
                    'end_date' => $v['end_date'],
                    'user_id' => $billInfo['user_id'],
                    'month_time' => $billInfo['month_time'],
                    'is_type' => $billInfo['is_type'],
                    'room_id' => $billInfo['room_id'] ?? '',
                    'property_id' => $billInfo['property_id'],
                    'contract_id' => $billInfo['contract_id'],
                ];
            }
        }
        return $this->dao->insertAll($insertData);
    }

    public function summaryBillSettlement(int $billId, array $data, $planInfo, $info = [])
    {
        $beilv = $data['beilv'] ?? 1;

        $data['basic_amount'] = $data['service_amount'] = $data['loss_amount'] = 0.00;
        # 单费率
        if ($planInfo['mode_type'] == 1) {
            # 用量
            $data['use_num_z'] = bcmul(bcsub($data['end_num_z'], $data['start_num_z'], 4), $beilv, 4);
            # 基础费用计算
            $data['basic_amount'] = bcmul($planInfo['basic_price'], $data['use_num_z'], 4);

            ##  服务费计算
            if ($planInfo['service_switch'] == 1) {
                $data['service_amount'] = bcmul($planInfo['service_price'], $data['use_num_z'], 4);
            }

        }

        # 多费率
        if ($planInfo['mode_type'] == 2) {
            # 用量
            $data['use_num_j'] = bcmul(bcsub($data['end_num_j'], $data['start_num_j'], 4), $beilv, 4);
            $data['use_num_f'] = bcmul(bcsub($data['end_num_f'], $data['start_num_f'], 4), $beilv, 4);
            $data['use_num_p'] = bcmul(bcsub($data['end_num_p'], $data['start_num_p'], 4), $beilv, 4);
            $data['use_num_g'] = bcmul(bcsub($data['end_num_g'], $data['start_num_g'], 4), $beilv, 4);

            $data['use_num_z'] = bcadd($data['use_num_j'], $data['use_num_f'], 4);
            $data['use_num_z'] = bcadd($data['use_num_z'], $data['use_num_p'], 4);
            $data['use_num_z'] = bcadd($data['use_num_z'], $data['use_num_g'], 4);

            $data['start_num_z'] = bcadd($data['start_num_j'], $data['start_num_f'], 4);
            $data['start_num_z'] = bcadd($data['start_num_z'], $data['start_num_p'], 4);
            $data['start_num_z'] = bcadd($data['start_num_z'], $data['start_num_g'], 4);

            $data['end_num_z'] = bcadd($data['end_num_j'], $data['end_num_f'], 4);
            $data['end_num_z'] = bcadd($data['end_num_z'], $data['end_num_p'], 4);
            $data['end_num_z'] = bcadd($data['end_num_z'], $data['end_num_g'], 4);

            # 基础费用计算
            $data['basic_amount_j'] = bcmul($planInfo['basic_price_j'], $data['use_num_j'], 4);
            $data['basic_amount_f'] = bcmul($planInfo['basic_price_f'], $data['use_num_f'], 4);
            $data['basic_amount_p'] = bcmul($planInfo['basic_price_p'], $data['use_num_p'], 4);
            $data['basic_amount_g'] = bcmul($planInfo['basic_price_g'], $data['use_num_g'], 4);

            $data['basic_amount'] = bcadd($data['basic_amount_j'], $data['basic_amount_f'], 4);
            $data['basic_amount'] = bcadd($data['basic_amount'], $data['basic_amount_p'], 4);
            $data['basic_amount'] = bcadd($data['basic_amount'], $data['basic_amount_g'], 4);

            ##  服务费计算
            if ($planInfo['service_switch'] == 1) {
                $data['service_amount_j'] = bcmul($planInfo['service_price_j'], $data['use_num_j'], 4);
                $data['service_amount_f'] = bcmul($planInfo['service_price_f'], $data['use_num_f'], 4);
                $data['service_amount_p'] = bcmul($planInfo['service_price_p'], $data['use_num_p'], 4);
                $data['service_amount_g'] = bcmul($planInfo['service_price_g'], $data['use_num_g'], 4);

                $data['service_amount'] = bcadd($data['service_amount_j'], $data['service_amount_f'], 4);
                $data['service_amount'] = bcadd($data['service_amount'], $data['service_amount_p'], 4);
                $data['service_amount'] = bcadd($data['service_amount'], $data['service_amount_g'], 4);
            }
        }

        # 阶梯率
        if ($planInfo['mode_type'] == 3) {
            # 用量
            $useNum = bcmul(bcsub($data['end_num_z'], $data['start_num_z'], 4), $beilv, 4);
            $data['use_num'] = $useNum;
            # 基础费用计算
            $basicAmount = 0;
            $stairPrice = $planInfo['stair_price'];
            foreach ($stairPrice as $k => $v) {
                if (isset($stairPrice[$k + 1])) {
                    $tempNum = $stairPrice[$k + 1]['fee_amount'] - $v['fee_amount'];
                    $tempNum = min($tempNum, $useNum);
                } else {
                    $tempNum = $useNum;
                }
                $basicAmount = bcadd($basicAmount, bcmul($tempNum, $v['fee_price'], 4), 4);
                $useNum -= $tempNum;
            }
            $data['basic_amount'] = $basicAmount;
            #服务费计算
            if ($planInfo['service_switch'] == 1) {
                $data['service_amount'] = bcmul($planInfo['service_price'], $data['use_num_z'], 4);
            }
        }

        ## 损耗费用计算
        if ($planInfo['loss_switch'] == 1) {
            $data['loss_amount'] = bcmul(bcadd($data['basic_amount'], $data['service_amount'], 4), $planInfo['loss_per'] / 100, 4);
        }
        $data['amount'] = bcadd($data['loss_amount'], bcadd($data['basic_amount'], $data['service_amount'], 4), 4);

        return $data;
    }

    /**
     * 任务生成账单
     * @param $contractInfo
     * @param $billInfo
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-12 21:50
     */
    public function taskContractOtherFee($contractInfo, $billInfo)
    {
        switch ($contractInfo['bill_month']) {
            case '1':
                ## 本月账单
                $data['start_date'] = date('Y-m-1');
                $data['end_date'] = date('Y-m-t');
                break;
            case '2':
                ## 次月账单
                $data['start_date'] = date('Y-m-1', strtotime('+1 month'));
                $data['end_date'] = date('Y-m-t', strtotime('+1 month'));
                break;
            case '3':
                ## 上月账单
                $data['start_date'] = date('Y-m-01', strtotime('last month'));
                $data['end_date'] = date('Y-m-t', strtotime('last month'));
                break;
        }
        /** @var ContractBillRepository $contractBillRepository */
        $contractBillRepository = app()->make(ContractBillRepository::class);
        $contractBillList = $contractBillRepository->getSearch([])
            ->where('status', '1')
            ->whereIn('if_bill', '2,3')
            ->where('contract_id', $contractInfo['id'])
            ->select();
        foreach ($contractBillList as $k => $v) {
            $data['is_type'] = $billInfo['is_type'];
            $data['status'] = $billInfo['status'];
            $data['amount'] = $v['amount'];
            $data['cate_id'] = $v['cate_id'];
            $data['bill_id'] = $billInfo['id'];
            $data['total_amount'] = $v['amount'];
            $data['user_id'] = $contractInfo['user_id'];
            $data['month_time'] = $billInfo['month_time'];
            $data['property_id'] = $billInfo['property_id'];
            $data['contract_id'] = $billInfo['contract_id'];
            $this->dao->create($data);
            if ($v['pay_type'] == 4) {
                # 一次性付
                $v->status = 9;
                $v->save();
            }
        }
        return true;
    }


    /**
     * 作废账单
     */
    public function batchInvalidBillCatalog(array $ids, int $userId, string $invalidRemark = '')
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids], ['status', 'in', [1, 2, 5, 8]]
        ], 'id,property_id,bill_id,status');
        if ($list) {
            $num = 0;
            foreach ($list as $k => $v) {
                $this->invalidBillCatalogInfo($v, $userId, $invalidRemark);
                $num++;
            }
            return $num;
        }
        return [];
    }

    public function invalidBillCatalogInfo($info, int $userId, string $invalidRemark = '')
    {
        return Db::transaction(function () use ($info, $userId, $invalidRemark) {
            $editData['status'] = 4;
            $this->dao->update($info['id'], $editData);

            # 账单明细作废事件
            event('bill.invalidCatalog', [
                'userId' => $userId,
                'catalogInfo' => $info,
                'invalidRemark' => $invalidRemark,
            ]);
        });
    }


    public function paymentBill($info, $param, int $userId)
    {
        return Db::transaction(function () use ($info, $param, $userId) {
            $picture = [];
            if (isset($param['picture'])) {
                $picture = $param['picture'];
                unset($param['picture']);
            }
            $payAmount = $info['stay_pay_amount'];
            /** @var BillCourseRepository $billCourseRepository */
            $billCourseRepository = app()->make(BillCourseRepository::class);
            $courseData['pay_type'] = 2;
            $courseData['check_type'] = 9;
            $courseData['check_method'] = 2;
            $courseData['bill_id'] = $info['bill_id'];
            $courseData['catalog_id'] = $info['id'];
            $courseData['room_id'] = $info['room_id'];
            $courseData['pay_remark'] = $param['remark'];
            $courseData['pay_amount'] = $payAmount;
            $courseData['pay_method'] = $param['pay_method'];
            $courseData['pay_time'] = date('Y_m-d H:i:s');
            $courseData['pay_user_id'] = $userId;
            $courseData['affirm_type'] = 1;
            $courseData['property_id'] = $info['property_id'];
            $resInfo = $billCourseRepository->create($courseData);
            if (isset($picture) && is_array($picture)) {
                /** @var BillPictureRepository $billPictureRepository */
                $billPictureRepository = app()->make(BillPictureRepository::class);
                $billPictureRepository->addPicture($info['bill_id'], $resInfo['id'], $picture, $info['id']);
            }
            $info->status = 9;
            $info->save();

            ## 账单支付事件
            event('bill.payCatalogSuccess', [
                'payType' => 2,
                'status' => 9,
                'userId' => $userId,
                'catalogInfo' => $info,
                'payAmount' => $payAmount,
                'payMethod' => $param['pay_method'],
            ]);
            return $resInfo;
        });
    }


    /**
     *  自定义支付账单
     * @param $info
     * @param $param
     * @param int $userId
     * @return mixed
     *
     * @author Amos
     * 2024-05-27 17:33
     */
    public function paymentCustomBill($info, $param, int $userId)
    {
        return Db::transaction(function () use ($info, $param, $userId) {
            $picture = [];
            if (isset($param['picture'])) {
                $picture = $param['picture'];
                unset($param['picture']);
            }
            /** @var BillCourseRepository $billCourseRepository */
            $billCourseRepository = app()->make(BillCourseRepository::class);
            $courseData['pay_type'] = 2;
            $courseData['check_type'] = 9;
            $courseData['check_method'] = 2;
            $courseData['bill_id'] = $info['bill_id'];
            $courseData['catalog_id'] = $info['id'];
            $courseData['pay_remark'] = $param['remark'];
            $courseData['pay_amount'] = $param['pay_amount'];
            $courseData['pay_method'] = $param['pay_method'];
            $courseData['pay_time'] = date('Y_m-d H:i:s');
            $courseData['pay_user_id'] = $userId;
            $courseData['affirm_type'] = 1;
            $courseData['room_id'] = $info['room_id'] ?? '0';
            $courseData['property_id'] = $info['property_id'];
            $resInfo = $billCourseRepository->create($courseData);
            if (isset($picture) && is_array($picture)) {
                /** @var BillPictureRepository $billPictureRepository */
                $billPictureRepository = app()->make(BillPictureRepository::class);
                $billPictureRepository->addPicture($info['bill_id'], $resInfo['id'], $picture, $info['id']);
            }
            if ($param['pay_amount'] < $info['stay_pay_amount']) {
                $info->status = 8;
            } else {
                $info->status = 9;
            }
            $info->save();

            ## 账单支付事件
            event('bill.payCatalogSuccess', [
                'payType' => 2,
                'status' => 9,
                'userId' => $userId,
                'catalogInfo' => $info,
                'payAmount' => $param['pay_amount'],
                'payMethod' => $param['pay_method'],
            ]);
            return $resInfo;
        });
    }


    /**
     * 根据物业 ID  查询租金汇总
     * @param $propertyId
     * @param int $propertyId
     * @param array $where
     * @return float|string
     *
     * @author Amos
     * 2024-06-14 10:14
     */
    public function getPropertyIdArrAmount(int $propertyId, array $where)
    {
        /** @var BillCateRepository $billCateRepository */
        $billCateRepository = app()->make(BillCateRepository::class);
        if (isset($where['is_class']) && $where['is_class'] > 0 && isset($where['set_finance']) && $where['set_finance'] > 0) {
            $cateId = $billCateRepository->getBillCateId($propertyId, ['is_class' => $where['is_class'], 'set_finance' => $where['set_finance']]);
        } else if (isset($where['is_class']) && $where['is_class'] > 0 && isset($where['set_finance']) && $where['set_finance'] <= 0) {
            $cateId = $billCateRepository->getBillCateIds($propertyId, $where['is_class']);
        } else {
            $cateId = 0;
        }

        return $this->dao->getSearch([])
            ->when($propertyId, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['month_time']) && $where['month_time'] !== '', function ($query) use ($where) {
                $query->where('month_time', $where['month_time']);
            })
            ->when(isset($where['is_type']) && $where['is_type'] !== '', function ($query) use ($where) {
                $query->where('is_type', $where['is_type']);
            })
            ->when(isset($where['status']) && $where['status'] !== '', function ($query) use ($where) {
                if (is_array($where['status'])) {
                    $query->whereIn('status', $where['status']);
                } else {
                    $query->where('status', (int)$where['status']);
                }
            })
            ->when($cateId, function ($query) use ($cateId) {
                if (is_array($cateId)) {
                    $query->whereIn('cate_id', $cateId);
                } else {
                    $query->where('cate_id', (int)$cateId);
                }
            })
            ->sum('total_amount');
    }

}